package cn.wolfcode.demo1.controller;

import cn.wolfcode.demo1.domain.User;
import cn.wolfcode.demo1.qo.JsonResult;
import cn.wolfcode.demo1.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @Controller 将Controller对象交给容器控制
 */
@Controller
public class UserController {
    /**
     * @RequestMapping("/") 配置对应的接口的访问路径
     */
    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletRequest request;
    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username,String password){
        User u = userService.login(username, password);
        if (u!=null){
            /**
             * 找到用户之后发送短信验证码
             * 并且将用户信息(包括验证码)进行存储
             */
            int code= (int) (Math.random()*9000+1000);
            userService.sendDX(u.getPhone(),code);
            request.getSession().setAttribute("code",code);
            request.getSession().setAttribute("user",u);
            return new JsonResult(true,"发送短信");
        }else{
            /**
             * 登录失败
             */
            return new JsonResult(false,"账户密码错误");
        }
    }

    @RequestMapping("/code")
    public String code(int code){
        Object user = request.getSession().getAttribute("user");
        int code1 = (int) request.getSession().getAttribute("code");
        if (user!=null && code==code1){
            return "redirect:/department/list";
        }else {
            return "redirect:/login.html";
        }
    }
}
